<template>
	<view class="offline-map-container">
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<text class="page-title">离线地图</text>
			<view class="right-space"></view>
		</view>

		<view class="content">
			<view class="section">
				<view class="section-header">
					<text class="section-title">已下载地图</text>
					<text class="storage-info">已用空间: {{ formatStorage(usedStorage) }}</text>
				</view>

				<view class="empty-tip" v-if="downloadedMaps.length === 0">
					<image src="/static/empty-map.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无已下载的离线地图</text>
				</view>

				<view class="map-list" v-else>
					<view class="map-item" v-for="(map, index) in downloadedMaps" :key="index">
						<view class="map-info">
							<text class="map-name">{{ map.name }}</text>
							<view class="map-meta">
								<text class="map-size">{{ formatStorage(map.size) }}</text>
								<text class="map-date">{{ formatDate(map.date) }}</text>
							</view>
						</view>
						<view class="map-actions">
							<view class="map-action update" v-if="map.needUpdate" @click="updateMap(map)">
								<text class="iconfont icon-update"></text>
							</view>
							<view class="map-action delete" @click="deleteMap(map)">
								<text class="iconfont icon-delete"></text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="section">
				<view class="section-header">
					<text class="section-title">城市离线地图</text>
				</view>

				<view class="search-box">
					<text class="iconfont icon-search"></text>
					<input type="text" v-model="searchKeyword" placeholder="搜索城市" @input="searchCity" />
				</view>

				<view class="city-list">
					<view class="city-category" v-for="(category, key) in filteredCityCategories" :key="key">
						<text class="category-title">{{ category.name }}</text>
						<view class="city-grid">
							<view class="city-item" v-for="(city, index) in category.cities" :key="index"
								@click="downloadCity(city)">
								<text class="city-name">{{ city.name }}</text>
								<view class="download-status" v-if="city.isDownloading">
									<text class="download-progress">{{ city.progress }}%</text>
								</view>
								<text class="download-btn" v-else>下载</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 地图容器 -->
		<view id="map" class="map-container"></view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from '../../hooks';

// 腾讯地图SDK实例
let map = null;
let offlineManager = null;

// 已下载的地图数据
const downloadedMaps = ref([]);
// 已用存储空间
const usedStorage = ref(0);
// 城市分类数据
const cityCategories = ref({
	hot: {
		name: '热门城市',
		cities: []
	},
	a_g: {
		name: 'A-G',
		cities: []
	},
	h_n: {
		name: 'H-N',
		cities: []
	},
	o_t: {
		name: 'O-T',
		cities: []
	},
	u_z: {
		name: 'U-Z',
		cities: []
	}
});
// 所有城市数据
const allCities = ref([]);
// 搜索关键词
const searchKeyword = ref('');

// 页面加载时
onMounted(() => {
	// 动态加载腾讯地图SDK
	const script = document.createElement('script');
	script.src = 'https://map.qq.com/api/gljs?v=1.exp&key=GDUBZ-PFPKG-OYAQE-QE6IK-TO6PH-TUFSR';
	script.async = true;
	script.onload = () => {
		// 初始化腾讯地图SDK
		initTencentMap();
		// 加载已下载的地图
		loadDownloadedMaps();
		// 加载城市列表
		loadCityList();
	};
	document.head.appendChild(script);
});

// 初始化腾讯地图SDK
const initTencentMap = () => {
	// 初始化地图实例
	map = new TMap.Map('map', {
		center: new TMap.LatLng(39.908802, 116.397502),
		zoom: 11
	});

	// 初始化离线管理器
	offlineManager = new TMap.OfflineManager({
		map: map,
		onComplete: (result) => {
			console.log('离线地图下载完成', result);
			loadDownloadedMaps(); // 重新加载已下载地图列表
		},
		onError: (error) => {
			console.error('离线地图下载错误', error);
			uni.showToast({
				title: '下载失败：' + error.message,
				icon: 'none'
			});
		},
		onProgress: (progress) => {
			// 更新下载进度
			const city = allCities.value.find(c => c.id === progress.id);
			if (city) {
				city.progress = Math.floor(progress.progress * 100);
			}
		}
	});
};

// 加载已下载的地图
const loadDownloadedMaps = () => {
	if (!offlineManager) return;

	// 获取所有已下载的城市
	offlineManager.getDownloadList((result) => {
		downloadedMaps.value = result.map(item => ({
			id: item.id,
			name: item.name,
			size: item.size,
			date: new Date(item.updateTime),
			needUpdate: item.needUpdate
		}));

		// 计算已用空间
		usedStorage.value = downloadedMaps.value.reduce((total, map) => total + map.size, 0);
	});
};

// 加载城市列表
const loadCityList = () => {
	// 模拟城市数据
	// 实际应用中应该从服务器获取
	allCities.value = [
		{ id: 1, name: '北京', firstLetter: 'B' },
		{ id: 2, name: '上海', firstLetter: 'S' },
		{ id: 3, name: '广州', firstLetter: 'G' },
		{ id: 4, name: '深圳', firstLetter: 'S' },
		{ id: 5, name: '杭州', firstLetter: 'H' },
		{ id: 6, name: '成都', firstLetter: 'C' },
		{ id: 7, name: '武汉', firstLetter: 'W' },
		{ id: 8, name: '西安', firstLetter: 'X' },
		{ id: 9, name: '南京', firstLetter: 'N' },
		{ id: 10, name: '重庆', firstLetter: 'C' },
		{ id: 11, name: '天津', firstLetter: 'T' },
		{ id: 12, name: '苏州', firstLetter: 'S' },
		{ id: 13, name: '长沙', firstLetter: 'C' },
		{ id: 14, name: '厦门', firstLetter: 'X' },
		{ id: 15, name: '青岛', firstLetter: 'Q' }
	];

	// 设置热门城市
	cityCategories.value.hot.cities = allCities.value.slice(0, 6).map(city => ({
		...city,
		isDownloading: false,
		progress: 0
	}));

	// 按字母分类
	allCities.value.forEach(city => {
		const letter = city.firstLetter.toUpperCase();
		if ('ABCDEFG'.includes(letter)) {
			cityCategories.value.a_g.cities.push({
				...city,
				isDownloading: false,
				progress: 0
			});
		} else if ('HIJKLMN'.includes(letter)) {
			cityCategories.value.h_n.cities.push({
				...city,
				isDownloading: false,
				progress: 0
			});
		} else if ('OPQRST'.includes(letter)) {
			cityCategories.value.o_t.cities.push({
				...city,
				isDownloading: false,
				progress: 0
			});
		} else {
			cityCategories.value.u_z.cities.push({
				...city,
				isDownloading: false,
				progress: 0
			});
		}
	});
};

// 搜索城市
const searchCity = () => {
	if (!searchKeyword.value) {
		// 重置分类
		loadCityList();
		return;
	}

	// 根据关键词过滤城市
	const keyword = searchKeyword.value.toLowerCase();
	const matchedCities = allCities.value.filter(city =>
		city.name.toLowerCase().includes(keyword)
	).map(city => ({
		...city,
		isDownloading: false,
		progress: 0
	}));

	// 清空所有分类
	Object.keys(cityCategories.value).forEach(key => {
		if (key !== 'hot') {
			cityCategories.value[key].cities = [];
		}
	});

	// 将匹配的城市放入搜索结果分类
	cityCategories.value.hot.name = '搜索结果';
	cityCategories.value.hot.cities = matchedCities;
};

// 下载城市地图
const downloadCity = (city) => {
	if (!offlineManager) return;

	// 检查是否已经下载
	const alreadyDownloaded = downloadedMaps.value.some(map => map.id === city.id);
	if (alreadyDownloaded) {
		uni.showToast({
			title: '该地图已下载',
			icon: 'none'
		});
		return;
	}

	// 设置下载状态
	city.isDownloading = true;
	city.progress = 0;

	// 开始下载
	offlineManager.download({
		id: city.id,
		name: city.name,
		success: () => {
			city.isDownloading = false;
			uni.showToast({
				title: '下载完成',
				icon: 'success'
			});
		},
		fail: (error) => {
			city.isDownloading = false;
			uni.showToast({
				title: '下载失败：' + error.message,
				icon: 'none'
			});
		}
	});
};

// 更新地图
const updateMap = (map) => {
	if (!offlineManager) return;

	uni.showLoading({
		title: '更新中...'
	});

	offlineManager.update({
		id: map.id,
		success: () => {
			map.needUpdate = false;
			map.date = new Date();
			uni.hideLoading();
			uni.showToast({
				title: '更新完成',
				icon: 'success'
			});
		},
		fail: (error) => {
			uni.hideLoading();
			uni.showToast({
				title: '更新失败：' + error.message,
				icon: 'none'
			});
		}
	});
};

// 删除地图
const deleteMap = (map) => {
	if (!offlineManager) return;

	uni.showModal({
		title: '删除确认',
		content: `确定要删除「${map.name}」离线地图吗？`,
		success: res => {
			if (res.confirm) {
				offlineManager.remove({
					id: map.id,
					success: () => {
						// 更新存储空间
						usedStorage.value -= map.size;

						// 从列表中移除
						const index = downloadedMaps.value.findIndex(item => item.id === map.id);
						if (index !== -1) {
							downloadedMaps.value.splice(index, 1);
						}

						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
					},
					fail: (error) => {
						uni.showToast({
							title: '删除失败：' + error.message,
							icon: 'none'
						});
					}
				});
			}
		}
	});
};

// 格式化存储大小
const formatStorage = (bytes) => {
	if (bytes < 1024) {
		return bytes + 'B';
	} else if (bytes < 1024 * 1024) {
		return (bytes / 1024).toFixed(1) + 'KB';
	} else if (bytes < 1024 * 1024 * 1024) {
		return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
	} else {
		return (bytes / (1024 * 1024 * 1024)).toFixed(1) + 'GB';
	}
};

// 格式化日期
const formatDate = (date) => {
	return date.getFullYear() + '-' +
		String(date.getMonth() + 1).padStart(2, '0') + '-' +
		String(date.getDate()).padStart(2, '0');
};

// 返回上一页
const goBack = () => {
	uni.navigateBack();
};

// 过滤后的城市分类数据
const filteredCityCategories = computed(() => {
	return Object.entries(cityCategories.value)
		.filter(([_, category]) => category.cities.length > 0)
		.reduce((acc, [key, category]) => {
			acc[key] = category;
			return acc;
		}, {});
});
</script>

<style>
.offline-map-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #f8f8f8;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background-color: #fff;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.back-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.icon-back {
	font-size: 40rpx;
	color: #333;
}

.page-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.right-space {
	width: 60rpx;
}

.content {
	flex: 1;
	padding: 20rpx;
}

.section {
	background-color: #fff;
	border-radius: 15rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1px solid #f5f5f5;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.storage-info {
	font-size: 24rpx;
	color: #999;
}

.empty-tip {
	padding: 60rpx 20rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 20rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.map-list {
	padding: 0 20rpx;
}

.map-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1px solid #f5f5f5;
}

.map-item:last-child {
	border-bottom: none;
}

.map-info {
	flex: 1;
}

.map-name {
	font-size: 30rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.map-meta {
	display: flex;
	font-size: 24rpx;
	color: #999;
}

.map-size {
	margin-right: 20rpx;
}

.map-actions {
	display: flex;
}

.map-action {
	width: 60rpx;
	height: 60rpx;
	border-radius: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-left: 10rpx;
}

.update {
	background-color: #007aff;
	color: #fff;
}

.delete {
	background-color: #ff3b30;
	color: #fff;
}

.search-box {
	display: flex;
	align-items: center;
	margin: 20rpx;
	background-color: #f5f5f5;
	border-radius: 10rpx;
	padding: 0 20rpx;
	height: 70rpx;
}

.icon-search {
	font-size: 32rpx;
	color: #999;
	margin-right: 10rpx;
}

.search-box input {
	flex: 1;
	height: 70rpx;
	font-size: 28rpx;
}

.city-list {
	padding: 0 20rpx 20rpx;
}

.city-category {
	margin-bottom: 20rpx;
}

.category-title {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 15rpx;
	display: block;
}

.city-grid {
	display: flex;
	flex-wrap: wrap;
}

.city-item {
	width: calc(33.33% - 20rpx);
	margin: 0 10rpx 20rpx;
	background-color: #f5f5f5;
	border-radius: 10rpx;
	padding: 20rpx 0;
	text-align: center;
	position: relative;
}

.city-name {
	font-size: 28rpx;
	color: #333;
	display: block;
	margin-bottom: 10rpx;
}

.download-btn {
	font-size: 24rpx;
	color: #007aff;
}

.download-status {
	height: 30rpx;
}

.download-progress {
	font-size: 24rpx;
	color: #007aff;
}

.map-container {
	position: fixed;
	top: -9999px;
	left: -9999px;
	width: 1px;
	height: 1px;
	z-index: -1;
}
</style>